/* 
 * Copyright (C) 2004-2005 Jonathan Bindel
 * Copyright (C) 2006-2007 Eskil Bylund 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

using System;
using System.Net;
using System.Net.Sockets;

namespace DCSharp.Backend.Connections
{
	public delegate void IncomingConnectionHandler(Socket socket);

	public sealed class TcpServer : Server
	{
		private static TcpServer instance;

		private IncomingConnectionHandler handler;

		public TcpServer(IPAddress localIP, int port,
			IncomingConnectionHandler handler) : base(localIP, port)
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			this.handler = handler;
		}

		#region Methods

		public static void StartListening(int port,
			IncomingConnectionHandler handler)
		{
			StopListening();

			instance = new TcpServer(IPAddress.Any, port, handler);
			instance.Start();
		}

		public static void StopListening()
		{
			if (instance != null)
			{
				instance.Stop();
				instance = null;
			}
		}

		protected override void ServerStart()
		{
			Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
				ProtocolType.Tcp);
			Listener.Bind(new IPEndPoint(LocalIP, Port));
			Listener.Listen(10);

			Listener.BeginAccept(new AsyncCallback(OnConnectRequest), Listener);
		}

		private void OnConnectRequest(IAsyncResult ar)
		{
			Socket listener = (Socket)ar.AsyncState;
			try
			{
				Socket client = listener.EndAccept(ar);
				handler(client);

				listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
			}
			catch (ObjectDisposedException)
			{
			}
		}
	}

	#endregion
}
